package com.hw.one.collect.movingsource.slagcar.job;

import cn.com.dekn.client.webservice.vehicleinfo.vo.ArrayOfCarPositionInfoVO;
import cn.com.dekn.client.webservice.vehicleinfo.vo.CarPositionInfoVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hw.one.collect.client.ClientFactory;
import com.hw.one.collect.dust.redis.BaseRedis;
import com.hw.one.collect.mapper.PatrolDeviceDao;
import com.hw.one.collect.movingsource.slagcar.constans.SlagCarConstants;
import com.hw.one.collect.movingsource.slagcar.dao.PatrolDataDao;
import com.hw.one.collect.movingsource.slagcar.po.PatrolDataPo;
import com.hw.one.collect.movingsource.slagcar.po.PatrolDevicePo;
import com.hw.one.collect.movingsource.slagcar.po.PatrolEntity;
import com.hw.one.collect.movingsource.slagcar.util.GpsChangeUtil;
import com.hw.one.collect.util.DateUtil;
import com.hw.one.collect.util.MessageProducer;
import org.apache.cxf.endpoint.Client;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Copyright 2017 汉威.智慧环保事业部.
 * Created by 李亚坤 on 2017/05/17 14:37.
 *
 * 市建委数据拉取任务
 */
@Component
public class SlagCarDataJob {

    private static Logger log = Logger.getLogger(SlagCarDataJob.class);

    private static DecimalFormat df = new DecimalFormat("#####.####");
    private static DecimalFormat df_0 = new DecimalFormat("#####");

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Resource
    private PatrolDeviceDao patrolDeviceDao;

    @Resource
    private PatrolDataDao patrolDataDao;

    @Resource
    private BaseRedis baseRedis;

    @Autowired
    private MessageProducer messageProducer;

    public void start() {
        Calendar calendar = Calendar.getInstance();
        //
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int min = calendar.get(Calendar.MINUTE);


        SlagCarConstants.getRegionIdWithName();
        Map<String, String[]> regionIdWithOtherCode = SlagCarConstants.regionIdWithOtherCode;
        log.info("-----------------------------请求链接---------------------");
        log.info(SlagCarConstants.SlagCar_URI);
        log.info("----------------------------------------------------------");

        // 创建客户端
        Client client = ClientFactory.newInstance().getClient(SlagCarConstants.SlagCar_URI, ClientFactory.slagCarType);
        List<PatrolDevicePo> patrolDeviceList = new ArrayList<>();
        List<PatrolDataPo> patrolDataList = new ArrayList<>();
        List<PatrolEntity> patrolEntityList = new ArrayList<>();
        for (String key : regionIdWithOtherCode.keySet()) {
            try {
                log.info("-------------------当前请求的城市：" + regionIdWithOtherCode.get(key)[0] + "-----------");

                // 构建查询参数
                Object[] e = client.invoke(SlagCarConstants.getVehicleInfo, key);

                if (e[0] instanceof CarPositionInfoVO) {
                    CarPositionInfoVO carPositionInfoVO = (CarPositionInfoVO) e[0];
                }else if (e[0] instanceof ArrayOfCarPositionInfoVO) {
                    ArrayOfCarPositionInfoVO arrayOfCarPositionInfoVO = (ArrayOfCarPositionInfoVO)e[0];
                    for (CarPositionInfoVO carPositionInfoVO : arrayOfCarPositionInfoVO.getCarPositionInfoVO()) {
                        if (!StringUtils.isEmpty(carPositionInfoVO.getCid())) {
                            // 处理数据

                            // 基础数据
                            PatrolDevicePo patrolDevicePo = new PatrolDevicePo();

                            patrolDevicePo.setIsUse("1");
                            patrolDevicePo.setCompanyName(carPositionInfoVO.getCompany());
                            patrolDevicePo.setDeviceType(4);
                            patrolDevicePo.setRegionCode(regionIdWithOtherCode.get(key)[1]); // 区域编码
                            patrolDevicePo.setUpdateTime(new Date());
                            patrolDevicePo.setCarCode(carPositionInfoVO.getNo());
                            patrolDevicePo.setDeviceName(carPositionInfoVO.getNo());
                            patrolDevicePo.setDeviceStatus("0");
                            patrolDevicePo.setId(UUID.randomUUID().toString());
                            patrolDevicePo.setDeviceCode(carPositionInfoVO.getCid());
                            patrolDeviceList.add(patrolDevicePo);

                            // 监测数据
                            PatrolDataPo patrolDataPo = new PatrolDataPo();
                            String monitorTime = StringUtils.isEmpty(carPositionInfoVO.getPositionTime()) ? "2017-01-01 00:00:00" : carPositionInfoVO.getPositionTime();
                            if (DateUtil.checkDate(sdf.parse(monitorTime), new Date())) {
                                log.info("----------数据比当前时间大，跳过");
                                continue;
                            }
                            patrolDataPo.setMONITORTIME(monitorTime);
                            patrolDataPo.setDEVICECODE(carPositionInfoVO.getCid());
                            patrolDataPo.setCREATETIME(sdf.format(new Date()));
                            // 行驶状态
                            patrolDataPo.setRUNSTATUS(carPositionInfoVO.getSpeedflag());
                            // 原始GPS数据
                            patrolDataPo.setGps(new double[]{Double.valueOf(carPositionInfoVO.getLongitude()), Double.valueOf(carPositionInfoVO.getLatitude())});
                            double[] wgs2bd = GpsChangeUtil.wgs2bd(patrolDataPo.getGps()[1], patrolDataPo.getGps()[0]);
                            // 转换为百度的坐标系
                            patrolDataPo.setLoc(new double[]{wgs2bd[1], wgs2bd[0]});
                            String lastTime = baseRedis.get("lastSlagCar" + carPositionInfoVO.getCid());
                            if (StringUtils.isEmpty(lastTime) || !lastTime.equals(patrolDataPo.getMONITORTIME())) {
                                patrolDataList.add(patrolDataPo);
                                baseRedis.insert("lastSlagCar" + carPositionInfoVO.getCid(), patrolDataPo.getMONITORTIME());
                            }
                            // 封装推送数据
                            PatrolEntity patrolEntity = new PatrolEntity();
                            patrolEntity.setAlarmStatus(StringUtils.isEmpty(patrolDataPo.getALARMSTATUS()) ? "-" : patrolDataPo.getALARMSTATUS());
                            patrolEntity.setCarCode(StringUtils.isEmpty(patrolDevicePo.getCarCode()) ? "-" : patrolDevicePo.getCarCode());
                            patrolEntity.setCompanyName(StringUtils.isEmpty(patrolDevicePo.getCompanyName()) ? "-" : patrolDevicePo.getCompanyName());
                            patrolEntity.setDeviceCode(StringUtils.isEmpty(patrolDevicePo.getDeviceCode()) ? "-" : patrolDevicePo.getDeviceCode());
                            patrolEntity.setDeviceName(StringUtils.isEmpty(patrolDevicePo.getDeviceName()) ? "-" : patrolDevicePo.getDeviceName());
                            patrolEntity.setDeviceStatus("-");
                            patrolEntity.setDeviceType("渣土车");
                            patrolEntity.setDeviceTypeCode("4");
                            patrolEntity.setLat(StringUtils.isEmpty(patrolDataPo.getLoc()[1]) ? "-" : String.valueOf(patrolDataPo.getLoc()[1]));
                            patrolEntity.setLng(StringUtils.isEmpty(patrolDataPo.getLoc()[0]) ? "-" : String.valueOf(patrolDataPo.getLoc()[0]));
                            String runStatus = StringUtils.isEmpty(patrolDataPo.getRUNSTATUS()) ? "-" : patrolDataPo.getRUNSTATUS();
                            if ("1".equals(runStatus)) {
                                runStatus = "正在行驶";
                            }
                            if ("0".equals(runStatus)) {
                                runStatus = "未行驶";
                            }
                            patrolEntity.setRunStatus(runStatus);
                            patrolEntity.setSiteStatus("0000");

                            patrolEntityList.add(patrolEntity);

                        }else {
                            System.out.println(carPositionInfoVO.getCompany());
                        }
                    }
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 保存数据到历史表
        patrolDataDao.savePatrolDataList(patrolDataList);
        // 更新数据到实时表
        patrolDataDao.updateRealRaiseDust(patrolDataList);
        messageProducer.sendMessage("movingExchange","", JSON.toJSONString(patrolEntityList));
        log.info("----------渣土车数据，本次总共请求到【"+patrolEntityList.size()+"】条数据------------------");
        // 如果是早上2点5分 时间，则更新基础数据
        if (hour == 2 && min < 5) {
            saveBaseInfo(patrolDeviceList);
        }
        log.info("----------渣土车数据，本次总共请求到【"+patrolDataList.size()+"】条数据------------------");
    }

    private void saveBaseInfo(List<PatrolDevicePo> patrolDeviceList) {
        for (PatrolDevicePo patrolDevicePo : patrolDeviceList) {
            List<PatrolDevicePo> resultList = patrolDeviceDao.findPatrolDeviceInfoByDeviceCode(patrolDevicePo.getDeviceCode());
            if (null == resultList || resultList.size() < 1) {
                patrolDeviceDao.insertPatrolDeviceSelective(patrolDevicePo);
            }else {
                patrolDeviceDao.updatePatrolByDeviceCodeSelective(patrolDevicePo);
            }
        }
    }



}
